<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import { ElButton, ElPopconfirm, ElTag } from 'element-plus';
import { useRoute } from 'vue-router';
import {
  fetchDeleteRoleRelation,
  fetchGetAuthorizeByPage,
  fetchGetDeptTraceTextById,
  fetchGetUserInfoById
} from '@/service/api';
import { $t } from '@/locales';
import { useTable, useTableOperate } from '@/hooks/common/table';
import RoleSearch from '@/views/system/role/modules/role-search.vue';
import RoleSelectDialog from '@/views/system/user-role/modules/role-select-dialog.vue';

defineOptions({ name: 'UserRoleManage' });

const route = useRoute();

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetAuthorizeByPage,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    condition: {
      objId: route.query.userId,
      type: 'USER'
    }
  },
  columns: () => [
    { type: 'selection', width: 48 },
    { prop: 'index', label: $t('common.index'), width: 64 },
    { prop: 'roleName', label: '角色名称', minWidth: 200, align: 'left' },
    { prop: 'roleCode', label: '角色编码', minWidth: 200, align: 'left' },
    {
      prop: 'dataScopeText',
      label: '数据范围',
      width: 150,
      align: 'center',
      formatter: row => <ElTag type="info">{row.dataScopeText}</ElTag>
    },
    {
      prop: 'enabled',
      label: $t('form.enabled'),
      width: 120,
      align: 'center',
      formatter: row => (
        <ElTag type={row.enabled === 1 ? 'success' : 'danger'}>
          {row.enabled === 1 ? $t('form.enabledOptions.enabled') : $t('form.enabledOptions.disabled')}
        </ElTag>
      )
    },
    {
      prop: 'operate',
      label: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 120,
      formatter: row => (
        <div class="flex-center">
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(row)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  // operateType,
  // editingData,
  handleAdd,
  // handleEdit,
  checkedRowKeys,
  // onBatchDeleted,
  onDeleted
} = useTableOperate(data, getData);

// 删除关联关系
async function handleDelete(row: Api.System.Role.RoleRelationRecord) {
  try {
    // request
    const { error } = await fetchDeleteRoleRelation(row);
    // success
    if (error) return;
    await onDeleted();
  } catch {
    //
  }
}

const userId = ref<CommonType.IdType>('');
const deptId = ref<CommonType.IdType>('');
const userInfo = ref<Api.System.User.UserInfoRecord>();

/** 获取用户信息 */
async function handleGetUserInfo() {
  const { data: info, error } = await fetchGetUserInfoById(userId.value);
  if (error) return;
  userInfo.value = info;
  if (deptId.value) {
    const { data: deptText, error: error1 } = await fetchGetDeptTraceTextById(deptId.value);
    if (error1) return;
    userInfo.value.deptText = deptText;
  }
}

onMounted(() => {
  userId.value = route.query.userId as string;
  deptId.value = route.query.deptId as string;
  handleGetUserInfo();
});
</script>

<template>
  <ElContainer>
    <ElHeader>
      <ElCard class="card-wrapper">
        <ElDescriptions :column="4" border label-width="80">
          <ElDescriptionsItem label="用户名">{{ userInfo?.username }}</ElDescriptionsItem>
          <ElDescriptionsItem label="昵称">{{ userInfo?.nickname || '未填写' }}</ElDescriptionsItem>
          <ElDescriptionsItem label="姓名">{{ userInfo?.fullname || '未填写' }}</ElDescriptionsItem>
          <ElDescriptionsItem label="手机号">{{ userInfo?.mobile || '未填写' }}</ElDescriptionsItem>
          <ElDescriptionsItem label="所在部门">{{ userInfo?.deptText || '暂未加入部门' }}</ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>
    </ElHeader>
    <ElHeader>
      <ElCard class="card-wrapper" :body-style="{ paddingTop: 0, paddingBottom: 0 }">
        <RoleSearch v-model="searchParams.condition" @reset="resetSearchParams" @search="getDataByPage" />
      </ElCard>
    </ElHeader>
    <ElMain>
      <ElCard class="h-full sm:flex-1-hidden card-wrapper">
        <template #header>
          <div class="flex flex-wrap items-center justify-between gap-5">
            <p>角色列表</p>
            <TableHeaderOperation
              v-model:columns="columnChecks"
              :disabled-delete="checkedRowKeys.length === 0"
              :loading="loading"
              @add="handleAdd"
              @refresh="getData"
            >
              <ElButton type="primary" plain @click="handleAdd">
                <template #icon>
                  <icon-ic-round-plus class="text-icon" />
                </template>
                新增授权
              </ElButton>
            </TableHeaderOperation>
          </div>
        </template>
        <div class="h-[calc(100%-45px)]">
          <ElTable
            v-loading="loading"
            height="100%"
            border
            class="sm:h-full"
            :data="data"
            row-key="id"
            show-overflow-tooltip
            @selection-change="checkedRowKeys = $event"
          >
            <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
          </ElTable>
        </div>
        <div class="mt15px flex justify-end">
          <ElPagination
            v-if="mobilePagination.total"
            background
            layout="total,prev,pager,next,sizes"
            v-bind="mobilePagination"
            @current-change="mobilePagination['current-change']"
            @size-change="mobilePagination['size-change']"
          />
        </div>
      </ElCard>
      <RoleSelectDialog
        v-model:visible="drawerVisible"
        type="USER"
        :obj-id="userInfo?.id"
        @submitted="getDataByPage(mobilePagination.currentPage)"
      />
    </ElMain>
  </ElContainer>
</template>

<style scoped>
.el-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .el-header {
    padding: 0;
    height: auto;
  }

  .el-main {
    padding: 0;
    height: 0;
    flex: 1;
  }
}

:deep(.el-card) {
  display: flex;
  flex-direction: column;
}

:deep(.el-card .el-card__body) {
  flex: 1;
  height: 0;
}

:deep(.el-table .cell) {
  padding: 0 10px;
}
</style>
